package cn.otrue.patienthealthmanager.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.adapter.SaleGoodsImageAdapter;
import cn.otrue.patienthealthmanager.bean.ImageStream;
import cn.otrue.patienthealthmanager.bean.TransferParameter;
import cn.otrue.patienthealthmanager.http.HttpCons;
import cn.otrue.patienthealthmanager.http.HttpServer;
import cn.otrue.patienthealthmanager.http.ServerHandler;
import cn.otrue.patienthealthmanager.utils.DialogUtil;
import cn.otrue.patienthealthmanager.utils.MyConst;
import cn.otrue.patienthealthmanager.utils.SendImageToRefund;
import cn.otrue.patienthealthmanager.view.GetPickResultListener;
import cn.otrue.patienthealthmanager.view.birthdaPopupWindow;

import com.google.gson.reflect.TypeToken;

/**
 * 个人中心->个人信息
 * 
 * @author G
 * 
 */
public class TiaoJiaBingliActivity extends BaseActivity {
	private TextView tv_title_title;
	private TextView tv_nian;
	private TextView tv_yue;
	private TextView tv_ri;
	private GridView iv_addimg;
	private List<ImageStream> images;
	private SaleGoodsImageAdapter goodsAdapters;
	private final int LOCALIMAGE = 10;
	private final int CAMERAIMAGE = 11;
	private List<Map<String, String>> puu;
	private String iiii;
	private TextView tv_title_back;
	private ImageStream uploadImageStream;
	private TextView tv_title_other;
	private Spinner sp_chufang;
	private ProgressDialog progress;
	private List<String> span;
	private birthdaPopupWindow windowwi;
	private View mainView;
	private String dateStr;
	private String back;
	private Context context;
	public static String name;
	private AlertDialog mDialog;
	private String dateStrs;

	// //////////////////////////////////////////////////////////////////////////首先加载数据，若数据为null则进入填写详细信息页
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.actiivity_tiaojia_bingli);
		initView();

	}

	class MyPickResultListener implements GetPickResultListener {

		@Override
		public void onGetResult(Object[] results, int type) {
			if (dateStr != null) {
				dateStr = results[0].toString();
				String[] dateArr = dateStr.split("-");
				tv_nian.setText(dateArr[0] + "年");
				tv_yue.setText(dateArr[1] + "月");
				tv_ri.setText(dateArr[2] + "日");
			} else {

			}

		}
	}

	private void initView() {
		initTitleBar();
		biaoti = (EditText) findViewById(R.id.biaoti);
		beizhu = (EditText) findViewById(R.id.beizhu);
		span = new ArrayList<String>();
		sp_chufang = (Spinner) findViewById(R.id.sp_chufang);
		mainView = findViewById(R.id.ll_tiaojia);
		tv_nian = (TextView) findViewById(R.id.tv_nian);
		calendar = Calendar.getInstance();
		tv_nian.setText(calendar.get(Calendar.YEAR) + "" + "年");

		tv_nian.setOnClickListener(this);
		tv_yue = (TextView) findViewById(R.id.tv_yue);
		tv_yue.setText(calendar.get(Calendar.MONTH) + 1 + "" + "月");
		tv_yue.setOnClickListener(this);
		tv_ri = (TextView) findViewById(R.id.tv_ri);
		tv_ri.setText(calendar.get(Calendar.DAY_OF_MONTH) + "" + "日");
		tv_ri.setOnClickListener(this);
		iv_addimg = (GridView) findViewById(R.id.iv_addimg);
		images = new ArrayList<ImageStream>();
		ImageStream imagestream = new ImageStream();
		imagestream.from = "+";
		imagestream.bitmap = BitmapFactory.decodeResource(getResources(),
				R.drawable.add01);
		images.add(imagestream);
		goodsAdapters = new SaleGoodsImageAdapter(this, images);

		iv_addimg.setAdapter(goodsAdapters);
		iv_addimg.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				if (position == images.size() - 1) {
					// 设置点击弹窗实现加图
					AlertDialog.Builder builder = new AlertDialog.Builder(
							TiaoJiaBingliActivity.this);
					builder.setTitle("选择图片");
					builder.setPositiveButton("本地上传", listener);
					builder.setNegativeButton("照相图片", listener);
					builder.create();
					builder.show();
				} else {

					File path = new File(images.get(position).path);
					Intent intent = new Intent();
					intent.setAction(android.content.Intent.ACTION_VIEW);
					intent.setDataAndType(Uri.fromFile(path), "image/*");
					startActivity(intent);
				}
			}
		});
		getsp();
	}

	public void initTitleBar() {
		tv_title_title = (TextView) findViewById(R.id.tv_title_title);
		tv_title_title.setText(getString(R.string.medicalrecordadd));
		tv_title_other = (TextView) findViewById(R.id.tv_title_other);
		tv_title_other.setText(getString(R.string.community_fatie));
		tv_title_other.setVisibility(View.VISIBLE);
		tv_title_other.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				uploadImageToServer();
				mDialog = DialogUtil.startProgressDialog(
						TiaoJiaBingliActivity.this, "正在加载......");

			}
		});

		tv_title_back = (TextView) findViewById(R.id.tv_title_back);
		tv_title_back.setVisibility(View.VISIBLE);
		tv_title_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

	}

	public void uploadImageToServer() {
		boolean isUpload = false; // 不上传
		int postion = 0;
		for (int i = 0; i < images.size(); i++) {
			if (images.get(i).from.equals("local") && !images.get(i).isUpload) {
				isUpload = true;
				postion = i;
				break;
			}
		}
		if (isUpload) {
			uploadImageStream = images.get(postion);
			new SendImageToRefund(uploadImageStream.path, this, Handler)
					.startThread();
		} else // 图片已上传完毕 ，或当没有图片时直接上传
		{
			if (isUpload) {

			}
			data();
		}

	}

	private void data() {
		HashMap<String, Object> map = new HashMap<String, Object>();
		int oooo = sp_chufang.getSelectedItemPosition() + 1;
		map.put("typeid", oooo);
		if (dateStr != null) {
			map.put("businesstime", dateStr);
		} else {
			String nian = calendar.get(Calendar.YEAR) + "";
			String yue = calendar.get(Calendar.MONTH) + 1 + "";
			String ri = calendar.get(Calendar.DAY_OF_MONTH) + "";
			dateStrs = nian + "-" + yue + "-" + ri;
			map.put("businesstime", dateStrs + "");
		}

		List<String> imageList = new ArrayList<String>();
		for (int i = 0; i < images.size() - 1; i++) {
			imageList.add(images.get(i).newName);
		}
		map.put("title", biaoti.getText().toString());
		map.put("imagepic", imageList);
		map.put("content", beizhu.getText().toString());
		map.put("functionId", 1);

		TransferParameter parameter = new TransferParameter();
		parameter.setUsername(MyConst.getACCOUNT());
		parameter.setPassword("");
		parameter.setData(map);
		new HttpServer().post(HttpCons.insertHistoryInfo, parameter,
				tiaojiaHandler);

	}

	private Handler tiaojiaHandler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			if (state.equals("001")) {
				if (mDialog != null && mDialog.isShowing()) {
					DialogUtil.endProgressDialog(mDialog);
				}
				finish();
				Toast.makeText(TiaoJiaBingliActivity.this, "操作成功", 0).show();
			} else {
				if (mDialog != null && mDialog.isShowing()) {
					DialogUtil.endProgressDialog(mDialog);
				}
				Toast.makeText(TiaoJiaBingliActivity.this, msg, 0).show();
			}
		}

		@Override
		public void onFail(Bundle data, String state) {
			if (mDialog != null && mDialog.isShowing()) {
				DialogUtil.endProgressDialog(mDialog);
			}
			if (state.equals(HttpCons.STATE_EXCEPTION)) {
				// 代表进入状态STATE_EXCEPTION 网络异常

				Toast.makeText(TiaoJiaBingliActivity.this, "网络异常,请稍后重试",
						Toast.LENGTH_SHORT).show();

			} else if (state.equals(HttpCons.STATE_FORMAT_ERROR)) {
				// 代表进入STATE_FORMAT_ERROR(不是Json)
			} else {
				// 代表进入STATE_ANALYTICAL_ERROR(Json解析错误)

			}
		}
	};

	private Handler Handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 15) {
				back = (String) msg.obj;
				try {
					JSONObject json = new JSONObject(back);
					if (json.getBoolean("status") == true) {
						String name = (String) json.get("newName");// 获取文件名
						String path = (String) json.get("photoPath");

						uploadImageStream.newName = name;
						uploadImageStream.isUpload = true;
						uploadImageToServer();
						Toast.makeText(TiaoJiaBingliActivity.this, "上传成功",
								Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(TiaoJiaBingliActivity.this, "上传失败",
								Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
	};

	private Handler spHandler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {

			String tuu = data.getString(HttpCons.DATA);

			if (state.equals("001")) {
				puu = HttpServer.gson.fromJson(tuu,
						new TypeToken<List<Map<String, String>>>() {
						}.getType());

				for (int i = 0; i < puu.size(); i++) {
					span.add(puu.get(i).get("typename"));
					iiii = puu.get(i).get("typeid").toString();
				}
				ArrayAdapter<String> spAdapter = new ArrayAdapter<String>(
						TiaoJiaBingliActivity.this,
						android.R.layout.simple_list_item_1, span);

				sp_chufang.setAdapter(spAdapter);

				Toast.makeText(TiaoJiaBingliActivity.this, "操作成功", 0).show();
			} else {
				Toast.makeText(TiaoJiaBingliActivity.this, "失败", 0).show();

			}
		}

		@Override
		public void onFail(Bundle data, String state) {

			if (state.equals(HttpCons.STATE_EXCEPTION)) {
				// 代表进入状态STATE_EXCEPTION 网络异常
				Toast.makeText(TiaoJiaBingliActivity.this, "网络异常,请稍后重试",
						Toast.LENGTH_SHORT).show();

			} else if (state.equals(HttpCons.STATE_FORMAT_ERROR)) {
				// 代表进入STATE_FORMAT_ERROR(不是Json)
			} else {
				// 代表进入STATE_ANALYTICAL_ERROR(Json解析错误)

			}
		}
	};

	private void getsp() {
		HashMap<String, Object> map = new HashMap<String, Object>();

		TransferParameter parameter = new TransferParameter();
		parameter.setUsername("");
		parameter.setPassword("");
		parameter.setData(map);
		new HttpServer().post(HttpCons.query_File_TypeInfo, parameter,
				spHandler);

	}

	private DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case DialogInterface.BUTTON_POSITIVE:
				Intent imageIntent = new Intent(
						Intent.ACTION_PICK,
						android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				startActivityForResult(imageIntent, LOCALIMAGE);
				break;
			case DialogInterface.BUTTON_NEGATIVE:
				Intent photoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(photoIntent, CAMERAIMAGE);
				break;
			}
		}
	};

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == 10 && data != null) { // local picture
				Uri uri = data.getData();
				Cursor cursor = getContentResolver().query(uri, null, null,
						null, null);// 获取系统数据：所有系统内保存的数据都可以通过
				cursor.moveToFirst();
				String imagePath = cursor.getString(1);
				cursor.close();
				Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
				Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
						bitmap.getHeight());
				// bitmap = zoomImage(bitmap, 100, 100);
				String path = saveBitmap(bitmap);

				ImageStream imagestream = new ImageStream();
				imagestream.from = "local";
				imagestream.bitmap = bitmap;
				imagestream.path = path;
				images.add(imagestream);
			}
			if (requestCode == 11 && data != null) { // phone with use
				Bundle bundle = data.getExtras();
				Bitmap bitmap = (Bitmap) bundle.get("data");
				// 缩放方图
				// bitmap = zoomImage(bitmap, 100, 100);
				String path = saveBitmap(bitmap);

				ImageStream imagestream = new ImageStream();
				imagestream.from = "local";
				imagestream.path = path;
				imagestream.bitmap = bitmap;
				images.add(imagestream);
			}
			images.remove(images.size() - 2);
			ImageStream imagestream = new ImageStream();
			imagestream.bitmap = BitmapFactory.decodeResource(getResources(),
					R.drawable.add01);
			imagestream.from = "+";
			images.add(imagestream);
			goodsAdapters.notifyDataSetChanged();
		}
	};

	/**
	 * 设置大小
	 * 
	 * @param bgimage
	 *            修改的图片
	 * @param newWidth
	 *            修改后图片的宽
	 * @param newHeight
	 *            修改后图片的高
	 * @return
	 */
	public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
			double newHeight) {
		// 获取这个图片的宽和高
		float width = bgimage.getWidth();
		float height = bgimage.getHeight();
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();

		// 计算宽高缩放率
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
				(int) height, matrix, true);
		return bitmap;
	}

	/**
	 * 保存图片并上传图片，保存一张保存一次路径
	 */
	private List<String> paths = new ArrayList<String>();

	private TextView TextView;
	private EditText beizhu;
	private EditText biaoti;
	private Calendar calendar;

	/**
	 * 将变化后的图片保存到本地：每次设置图片后都会保存下来并将路径保存到集合
	 * 
	 * @param bitmap
	 *            要保存的图片
	 * @return 是否保存成功
	 */
	public String saveBitmap(Bitmap bitmap) {
		boolean success = false;
		File file = null;
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			File sdcardPath = Environment.getExternalStorageDirectory();// 获取sd卡目录
			File dir = new File(sdcardPath, "saleImageFile");// 在该目录下创建文件
			if (!dir.exists()) {
				dir.mkdirs();
			}
			Date date = new Date();// 时间要用util包
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			String fileName = dateFormat.format(date) + ".jpg";
			file = new File(dir, fileName);
			Log.e("ERROR", file.getAbsolutePath());
			try {
				bitmap = zoomImage(bitmap, bitmap.getWidth() / 2,
						bitmap.getHeight() / 2);
				success = bitmap.compress(Bitmap.CompressFormat.JPEG, 100,
						new FileOutputStream(file));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		} else {
			Toast.makeText(this, "sdk不可用", Toast.LENGTH_LONG).show();
		}
		return file.getAbsolutePath();
	}

	private boolean verifyPicSize() {
		boolean isValide = true; // 有效

		for (int i = 0; i < images.size(); i++) {
			if (images.get(i).from.equals("local") && !images.get(i).isUpload) {
				if (images.get(i).bitmap.getByteCount() > MyConst.maxuploadbytes) {
					Log.i("pic=",
							String.valueOf(images.get(i).bitmap.getByteCount()));
					Log.i("maxup=", String.valueOf(MyConst.maxuploadbytes));
					isValide = false; // 超过限制
					break;
				}
			}
		}

		return isValide;
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.tv_nian:

			windowwi = new birthdaPopupWindow(this, new MyPickResultListener());
			windowwi.setBackgroundDrawable(new BitmapDrawable());
			windowwi.showAtLocation(mainView, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);

			break;
		case R.id.tv_yue:

			windowwi = new birthdaPopupWindow(this, new MyPickResultListener());
			windowwi.setBackgroundDrawable(new BitmapDrawable());
			windowwi.showAtLocation(mainView, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);

			break;
		case R.id.tv_ri:

			windowwi = new birthdaPopupWindow(this, new MyPickResultListener());
			windowwi.setBackgroundDrawable(new BitmapDrawable());
			windowwi.showAtLocation(mainView, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);

			break;

		}
	}
}
